package com.kgcx.common.interceptor;

import com.kgcx.common.constant.Cons;
import com.kgcx.common.utils.ApplicationUtils;
import com.kgcx.common.utils.TokenUtils;
import com.kgcx.common.utils.ValidateUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 是否需要请求鉴权，由于业务服务不对外开放,只针对网关开放,所以一般不需要开启
     */
    @Value("${kgcx.auth.enable:false}")
    boolean authEnable;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (authEnable) {
            String timestamp = DateFormatUtils.format(System.currentTimeMillis(), Cons.DATE_FORMAT_YYYYMMDDHHMMSSSSS);
            requestTemplate.header("timestamp", timestamp);
            log.debug("timestamp=" + timestamp);

            String paramString = ValidateUtils.sortParamForFeign(requestTemplate.queries());
            log.debug("paramString=" + paramString);

            String signature = ValidateUtils.generateSignature(timestamp, paramString);
            requestTemplate.header("signature", signature);
            log.debug("signature=" + signature);
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String token = null;
        if (null != requestAttributes) {
            /**
             * 如果是从网关过来的请求，则把原有token直接传递到下一个请求的服务中做鉴权
             */
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            token = request.getHeader("token");
        }
        if (StringUtils.isEmpty(token)) {
            /**
             * 如果不是从网关过来的请求，比如mq触发或者其他
             * 则以服务名为id生成一个token传递到下一个请求的服务中做鉴权
             */
            token = TokenUtils.getToken(ApplicationUtils.getApplicationName()
                    , TokenUtils.TOKEN_SUBJECT_SERVER);
        }
        requestTemplate.header("token", token);
        log.debug("token=" + token);
    }
}
